import React, { createContext, useState, useEffect, useContext } from 'react';

// 创建认证上下文
const AuthContext = createContext();

// 提供认证上下文的Provider组件
export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);

  // 初始化时从localStorage中获取用户信息
  useEffect(() => {
    const storedUser = localStorage.getItem('eduverse_user');
    if (storedUser) {
      try {
        setCurrentUser(JSON.parse(storedUser));
      } catch (error) {
        console.error('解析用户数据失败:', error);
        localStorage.removeItem('eduverse_user');
      }
    }
    setLoading(false);
  }, []);

  // 登录函数
  const login = (userData) => {
    setCurrentUser(userData);
    localStorage.setItem('eduverse_user', JSON.stringify(userData));
  };

  // 登出函数
  const logout = () => {
    setCurrentUser(null);
    localStorage.removeItem('eduverse_user');
  };

  // 更新用户数据
  const updateUser = (userData) => {
    setCurrentUser(prevUser => ({
      ...prevUser,
      ...userData
    }));
    localStorage.setItem('eduverse_user', JSON.stringify({
      ...currentUser,
      ...userData
    }));
  };

  const value = {
    currentUser,
    login,
    logout,
    updateUser,
    isAuthenticated: !!currentUser
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
};

// 自定义钩子以便于使用认证上下文
export const useAuth = () => useContext(AuthContext); 